package com.top4create.webapp.controller;

import org.apache.commons.lang.StringUtils;
import com.top4create.service.GenericManager;
import com.top4create.model.User;
import com.top4create.webapp.controller.BaseFormController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Controller
@RequestMapping("/userform*")
public class UserFormController extends BaseFormController {
    private GenericManager<User, Long> userManager = null;

    @Autowired
    public void setUserManager(@Qualifier("userManager") GenericManager<User, Long> userManager) {
        this.userManager = userManager;
    }

    public UserFormController() {
        setCancelView("redirect:/users");
        setSuccessView("redirect:/users");
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected User showForm(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            return userManager.get(new Long(id));
        }

        return new User();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(User user, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
    throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (user.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            userManager.remove(user.getId());
            saveMessage(request, getText("user.deleted", locale));
        } else {
            userManager.save(user);
            String key = (isNew) ? "user.added" : "user.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                success = "redirect:/userform?id=" + user.getId();
            }
        }

        return success;
    }
}
